package com.example.workmode;

import java.text.DateFormatSymbols;
import java.util.Calendar;
import java.util.GregorianCalendar;

import com.example.workmode.TaskCursorAdapter;
import com.example.workmode.Content.TaskContract;

import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.TextView;

public class ToDoListFragment extends Fragment  {

	private View view;
	private EditText newtask;
	private Button addbutton;
	private TextView dpicker;
	private String todaydate = "28Nov";
	private String duedate = "28Nov";
	private String name = "Mobile App";
	
	private TaskCursorAdapter adapter;
	
	static private final Uri task_provider = TaskContract.Task.CONTENT_URI;
	static private String log_tag = "workmode";

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		
		
		view = inflater.inflate(R.layout.fragment_to_do_list, container, false);

		 //Date picker
		dpicker = (EditText) view.findViewById(R.id.datepicker);
		//Add task 
		newtask = (EditText) view.findViewById(R.id.newtask);
		addbutton = (Button) view.findViewById(R.id.addbutton);
		addbutton.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {

				name = newtask.getText().toString();
				duedate = dpicker.getText().toString();
				int num_rows_updated = update(name, duedate, "N");
				Toast.makeText(getActivity().getBaseContext(), num_rows_updated + " rows updated", Toast.LENGTH_SHORT).show();

			}
			
		});
		
		//List
		Cursor cursor = getActivity().getContentResolver().query(task_provider, null, null, null, null);
		
		ListView list = (ListView) view.findViewById(R.id.list);
		adapter = new TaskCursorAdapter(getActivity(), R.layout.row_layout, cursor, 1);
		list.setAdapter(adapter);
		

		//getLoaderManager().initLoader(0, null, this);
		
		//set listeners for list

	    list.setOnItemClickListener(new ListView.OnItemClickListener() {
	        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
	        	
	        	String Name = ((TextView)view.findViewById(R.id.name)).getText().toString();
	        	//duedate = ((TextView)view.findViewById(R.id.duedate)).getText().toString();
	        	//mark as today
				mark(Name);
				
				
	       }
	    });
	    list.setOnItemLongClickListener(new ListView.OnItemLongClickListener() {
	        @Override
	        public boolean onItemLongClick(AdapterView<?> parent, View view,int position, long id) {
	        	
	        	String Name = ((TextView)view.findViewById(R.id.name)).getText().toString();
	        	dialog(Name);
            	
				return true;
	        }
	    });
	    
	   
	  
         
         
         /*dpicker.setOnClickListener(new View.OnClickListener() {
        	    @Override
        	    public void onClick(View v) {
        	    	DialogFragment newFragment = new DatePickerFragment();
        	        newFragment.show(getActivity().getSupportFragmentManager(), "datePicker");
        	    }
        	});*/
		
		 return view;
	}
  /*             
	public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			// Use the current date as the default date in the picker
			final Calendar c = Calendar.getInstance();
			int year = c.get(Calendar.YEAR);
			int month = c.get(Calendar.MONTH);
			int day = c.get(Calendar.DAY_OF_MONTH);

			// Create a new instance of DatePickerDialog and return it
			return new DatePickerDialog(getActivity(), this, year, month, day);
		}

		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			// Do something with the date chosen by the user
			String monthString = new DateFormatSymbols().getMonths()[monthOfYear-1];
			String date = Integer.toString(dayOfMonth) + " " + monthString + Integer.toString(year);
			dpicker.setText(date);

		}
  }
	/*
	public void showDatePickerDialog(View v) {
	    DialogFragment newFragment = new DatePickerFragment();
	    newFragment.show(getFragmentManager(), "datePicker");
	}
	*/
	
	protected void dialog(final String Name) {
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		builder.setMessage(R.string.delete_message).setTitle(R.string.delete_title);
		
		builder.setPositiveButton("Yes", new AlertDialog.OnClickListener() {
		@Override
		public void onClick(DialogInterface dialog, int which) {
			dialog.dismiss();	
			delete(Name);
		}
		});
		
		builder.setNegativeButton("No", new AlertDialog.OnClickListener() {
		  @Override
		  public void onClick(DialogInterface dialog, int which) {
			  dialog.dismiss();
			  }
		  });
		builder.create().show();
	}

    
    // find name
    private Cursor find(String name)
    {
    	Cursor cursor = null;
    	
    	if(TextUtils.isEmpty(name))
    	{
    		cursor = null;
    	}
    	else
    	{
        	String selection_clause = TaskContract.Task.NAME + " = ?";
        	String[] selection_args = {""};
        	selection_args[0] = name;
        	
    		cursor = getActivity().getContentResolver().query(task_provider, null, selection_clause, selection_args, null);
    	}
    	
    	return cursor;
    }
    
    // delete name
    private int delete(String name)
    {
		int num_rows_deleted = 0;
		
		try
		{
			if(TextUtils.isEmpty(name))
			{
				num_rows_deleted = getActivity().getContentResolver().delete(task_provider, null, null);
			}
			else
			{
	        	String selection_clause = TaskContract.Task.NAME + " = ?";
	        	String[] selection_args = {""};
	        	selection_args[0] = name;
	        	
				num_rows_deleted = getActivity().getContentResolver().delete(task_provider, selection_clause, selection_args);
			}
		}
		catch(Exception e)
		{
			final String error_message = "error in deleting";
			Toast.makeText(getActivity().getBaseContext(), error_message, Toast.LENGTH_SHORT).show();
			Log.e(log_tag, error_message);
		}
		
		return num_rows_deleted;
    }
    
    // insert
    private int insert(String name, String date, String today)
    {
    	int num_rows_updated = 0;
    	
		ContentValues content_values = new ContentValues();
		content_values.put(TaskContract.Task.NAME, name);
		content_values.put(TaskContract.Task.DUEDATE, date);
		content_values.put(TaskContract.Task.TODAY, today);
		
		try
		{
			getActivity().getContentResolver().insert(task_provider, content_values);
			num_rows_updated++;
		}
		catch(Exception e)
		{
			final String error_message = "error in inserting " + name;
			Toast.makeText(getActivity().getBaseContext(), error_message, Toast.LENGTH_SHORT).show();
			Log.e(log_tag, error_message);
		}
		
		return num_rows_updated;
    }
    
    // update: only for adding
    private int update(String name, String date, String today)
    {
		Cursor cursor = find(name);
		
		int num_rows_updated = 0;
		
		if((cursor == null) || (cursor.getCount() <= 0))
		{
			if(TextUtils.isEmpty(name))
			{
				// do nothing as no need to add empty word
			}
			else
			{
				num_rows_updated = insert(name, date, today);
			}
		}
		else
		{
			ContentValues update_values = new ContentValues();
			update_values.put(TaskContract.Task.NAME, name);
			update_values.put(TaskContract.Task.DUEDATE, date);
			update_values.put(TaskContract.Task.TODAY, today);

			try
			{
				String selection_clause = TaskContract.Task.NAME + " = ?";
				String[] selection_args = {""};
				selection_args[0] = name;

				num_rows_updated = getActivity().getContentResolver().update(task_provider, update_values, selection_clause, selection_args);
			}
			catch(Exception e)
			{
				final String error_message = "error in updating " + name;
				Toast.makeText(getActivity().getBaseContext(), error_message, Toast.LENGTH_SHORT).show();
				Log.e(log_tag, error_message);
			}
		}
		
		return num_rows_updated;
	}
    
    // mark as today
    private int mark(String name)
    {
		Cursor cursor = find(name);
		
		int num_rows_marked = 0;
		
		if((cursor == null) || (cursor.getCount() <= 0))
		{
			if(TextUtils.isEmpty(name))
			{
				// do nothing as no need to add empty word
			}
			else
			{
				Toast.makeText(getActivity().getApplicationContext(), "not found " +
						name, Toast.LENGTH_SHORT).show();
			}
		}
		else
		{
			/*ContentValues update_values = new ContentValues();
			update_values.put(TaskContract.Task.NAME, name);
			update_values.put(TaskContract.Task.DUEDATE, duedate);
			update_values.put(TaskContract.Task.TODAY, "Y");*/
			
			try
			{
				/*String selection_clause = TaskContract.Task.TODAY + " = ?";
				String[] selection_args = {""};
				selection_args[0] = name;*/
				//if (cursor.getString(cursor.getColumnIndex("today")).equals("Y")) {
					//update(name, cursor.getString(cursor.getColumnIndex("duedate")), "N");
				//} else {
					update(name, todaydate, "Y");
				//}

				//num_rows_marked = getActivity().getContentResolver().update(task_provider, update_values, selection_clause, selection_args);
				Toast.makeText(getActivity().getApplicationContext(), "marked as today " +
						name, Toast.LENGTH_SHORT).show();
			}
			catch(Exception e)
			{
				final String error_message = "error in marking " + name;
				Toast.makeText(getActivity().getBaseContext(), error_message, Toast.LENGTH_SHORT).show();
				Log.e(log_tag, error_message);
			}
		}
		//cursor = getActivity().getContentResolver().query(task_provider, null, null, null, null);
		return num_rows_marked;
	}
    
    private boolean isToday(String name){
    	Cursor cursor = find(name);

		if((cursor == null) || (cursor.getCount() <= 0))
		{
			if(TextUtils.isEmpty(name))
			{
				// do nothing as no need to add empty word
			}
			else
			{
				Toast.makeText(getActivity().getBaseContext(), "not found", Toast.LENGTH_SHORT).show();
			}
		}
		else {
			String column = cursor.getString(1);
			Toast.makeText(getActivity().getBaseContext(), column, Toast.LENGTH_SHORT).show();
		}
		return false;
    }
			
            
}
/*
	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle args) {
		
		CursorLoader loader = new CursorLoader(getActivity(), 
				task_provider, 
				null, 
				null, 
				null, 
				null); 
		return loader;
	}


	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
		adapter.swapCursor(data);
		
	}


	@Override
	public void onLoaderReset(Loader<Cursor> loader) {
		adapter.swapCursor(null);
		
	}
*/



